import React, { useEffect, useState, useCallback } from 'react';
import {
  Card,
  Table,
  Button,
  Input,
  Select,
  Space,
  Tag,
  DatePicker,
  message,
  Row,
  Col,
  Statistic,
  Avatar,
  Typography,
  Tooltip,
  Badge,
  Popconfirm,
  Modal,
  Descriptions,
} from 'antd';
import {
  SearchOutlined,
  EyeOutlined,
  EditOutlined,
  DeleteOutlined,
  ExportOutlined,
  ReloadOutlined,
  ShoppingCartOutlined,
  DollarOutlined,
  ClockCircleOutlined,
  CheckCircleOutlined,
} from '@ant-design/icons';
import type { ColumnsType, TableRowSelection } from 'antd/es/table';
import { useNavigate } from 'react-router-dom';
import { useAppDispatch, useAppSelector } from '../../store';
import { setBreadcrumbs } from '../../store/slices/uiSlice';
import { fetchOrders } from '../../store/slices/orderSlice';

const { Title, Text } = Typography;
const { Search } = Input;
const { Option } = Select;
const { RangePicker } = DatePicker;

interface OrderItem {
  id: string;
  productId: string;
  productName: string;
  productImage: string;
  price: number;
  quantity: number;
  specifications?: Record<string, string>;
}

interface Order {
  id: string;
  orderNo: string;
  userId: string;
  userName: string;
  userAvatar?: string;
  shopId: string;
  shopName: string;
  items: OrderItem[];
  totalAmount: number;
  discountAmount: number;
  shippingFee: number;
  finalAmount: number;
  status: 'pending' | 'paid' | 'shipped' | 'delivered' | 'cancelled' | 'refunded';
  paymentMethod: 'alipay' | 'wechat' | 'credit_card' | 'cash';
  paymentStatus: 'unpaid' | 'paid' | 'refunded';
  shippingAddress: {
    name: string;
    phone: string;
    address: string;
  };
  trackingNumber?: string;
  remark?: string;
  createdAt: string;
  updatedAt: string;
  paidAt?: string;
  shippedAt?: string;
  deliveredAt?: string;
}

interface OrderListState {
  orders: Order[];
  loading: boolean;
  total: number;
  current: number;
  pageSize: number;
  selectedRowKeys: React.Key[];
  searchKeyword: string;
  filters: {
    status: string;
    paymentStatus: string;
    paymentMethod: string;
    shopId: string;
    dateRange: [string, string] | null;
  };
}

const OrderList: React.FC = () => {
  const dispatch = useAppDispatch();
  const navigate = useNavigate();

  // 从Redux store获取订单数据
  const { orders, loading, total, pagination } = useAppSelector(state => state.order);

  // 本地状态管理
  const [state, setState] = useState({
    selectedRowKeys: [] as string[],
    searchKeyword: '',
    filters: {
      status: '',
      paymentStatus: '',
      paymentMethod: '',
      shopId: '',
      dateRange: null,
    },
  });

  // 设置面包屑
  useEffect(() => {
    dispatch(setBreadcrumbs([
      { title: '订单管理' },
      { title: '订单列表' },
    ]));
  }, [dispatch]);

  // 加载订单数据
  const loadOrders = useCallback(async () => {
    const params = {
      page: pagination.current,
      limit: pagination.pageSize,
      keyword: state.searchKeyword,
      status: state.filters.status,
      paymentStatus: state.filters.paymentStatus,
      paymentMethod: state.filters.paymentMethod,
    };

    dispatch(fetchOrders(params));
  }, [dispatch, pagination.current, pagination.pageSize, state.searchKeyword, state.filters]);

  // 初始加载
  useEffect(() => {
    loadOrders();
  }, [loadOrders]);

  // 获取订单状态标签
  const getStatusTag = (status: string) => {
    const statusConfig = {
      '待付款': { color: 'orange', text: '待付款' },
      '待发货': { color: 'blue', text: '待发货' },
      '已发货': { color: 'cyan', text: '已发货' },
      '已完成': { color: 'green', text: '已完成' },
      '已取消': { color: 'red', text: '已取消' },
      '已退款': { color: 'purple', text: '已退款' },
      '退款中': { color: 'gold', text: '退款中' },
    };
    const config = statusConfig[status as keyof typeof statusConfig] || { color: 'default', text: status };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  // 获取支付方式标签
  const getPaymentMethodTag = (method: string) => {
    const methodConfig = {
      alipay: { color: 'blue', text: '支付宝' },
      wechat: { color: 'green', text: '微信支付' },
      credit_card: { color: 'gold', text: '信用卡' },
      cash: { color: 'default', text: '现金' },
    };
    const config = methodConfig[method as keyof typeof methodConfig] || { color: 'default', text: method };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  // 行选择
  const rowSelection: TableRowSelection<Order> = {
    selectedRowKeys: state.selectedRowKeys,
    onChange: (selectedRowKeys) => {
      setState(prev => ({ ...prev, selectedRowKeys }));
    },
  };

  // 表格列定义
  const columns: ColumnsType<Order> = [
    {
      title: '订单信息',
      key: 'orderInfo',
      width: 200,
      render: (_, record) => (
        <div>
          <div style={{ fontWeight: 500, marginBottom: 4 }}>
            {record.orderNo}
          </div>
          <div style={{ fontSize: 12, color: '#666' }}>
            {new Date(record.createdAt).toLocaleString()}
          </div>
        </div>
      ),
    },
    {
      title: '用户信息',
      key: 'userInfo',
      width: 150,
      render: (_, record) => (
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <Avatar
            src={record.userAvatar}
            size="small"
            style={{ marginRight: 8 }}
          >
            {record.userName[0]}
          </Avatar>
          <div>
            <div style={{ fontWeight: 500 }}>{record.userName}</div>
            <div style={{ fontSize: 12, color: '#666' }}>
              ID: {record.userId}
            </div>
          </div>
        </div>
      ),
    },
    {
      title: '商品信息',
      key: 'products',
      width: 250,
      render: (_, record) => (
        <div>
          {record.orderItems?.slice(0, 2).map((item, index) => (
            <div key={item.id} style={{ display: 'flex', alignItems: 'center', marginBottom: index < 1 ? 4 : 0 }}>
              <img
                src={item.image || 'https://via.placeholder.com/30x30/f0f0f0/999999?text=商品'}
                alt={item.name}
                style={{
                  width: 30,
                  height: 30,
                  borderRadius: 4,
                  marginRight: 8,
                  objectFit: 'cover',
                  backgroundColor: '#f5f5f5'
                }}
                onError={(e) => {
                  e.currentTarget.src = 'https://via.placeholder.com/30x30/f0f0f0/999999?text=商品';
                }}
              />
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 12 }}>{item.name}</div>
                <div style={{ fontSize: 11, color: '#666' }}>
                  ¥{item.price} × {item.quantity}
                </div>
              </div>
            </div>
          ))}
          {(record.orderItems?.length || 0) > 2 && (
            <div style={{ fontSize: 12, color: '#666' }}>
              等{record.orderItems?.length}件商品
            </div>
          )}
        </div>
      ),
    },
    {
      title: '订单金额',
      key: 'amount',
      width: 120,
      render: (_, record) => (
        <div>
          <div style={{ fontWeight: 500, color: '#f50' }}>
            ¥{record.totalPrice?.toFixed(2) || '0.00'}
          </div>
          <div style={{ fontSize: 12, color: record.isPaid ? '#52c41a' : '#999' }}>
            {record.isPaid ? '已支付' : '未支付'}
          </div>
        </div>
      ),
    },
    {
      title: '订单状态',
      dataIndex: 'orderStatus',
      key: 'orderStatus',
      width: 100,
      filters: [
        { text: '待付款', value: '待付款' },
        { text: '待发货', value: '待发货' },
        { text: '已发货', value: '已发货' },
        { text: '已完成', value: '已完成' },
        { text: '已取消', value: '已取消' },
        { text: '已退款', value: '已退款' },
        { text: '退款中', value: '退款中' },
      ],
      render: (status) => getStatusTag(status),
    },
    {
      title: '支付方式',
      dataIndex: 'paymentMethod',
      key: 'paymentMethod',
      width: 100,
      render: (method) => getPaymentMethodTag(method || '未选择'),
    },
    {
      title: '操作',
      key: 'actions',
      width: 120,
      fixed: 'right',
      render: (_, record) => (
        <Space>
          <Tooltip title="查看详情">
            <Button
              type="text"
              size="small"
              icon={<EyeOutlined />}
              onClick={() => navigate(`/orders/${record.id}`)}
            />
          </Tooltip>
          <Tooltip title="编辑">
            <Button
              type="text"
              size="small"
              icon={<EditOutlined />}
              onClick={() => navigate(`/orders/${record.id}/edit`)}
            />
          </Tooltip>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      {/* 统计卡片 */}
      <Row gutter={16} style={{ marginBottom: '24px' }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="订单总数"
              value={total}
              prefix={<ShoppingCartOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="待付款"
              value={orders.filter(o => o.orderStatus === '待付款').length}
              prefix={<ClockCircleOutlined />}
              valueStyle={{ color: '#faad14' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="已完成"
              value={orders.filter(o => o.orderStatus === '已完成').length}
              prefix={<CheckCircleOutlined />}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="总销售额"
              value={orders.reduce((sum, order) => sum + (order.totalPrice || 0), 0)}
              precision={2}
              prefix="¥"
              valueStyle={{ color: '#f50' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 操作栏 */}
      <Card style={{ marginBottom: '16px' }}>
        <Row gutter={16} align="middle">
          <Col flex="auto">
            <Space>
              <Search
                placeholder="搜索订单号、用户名..."
                style={{ width: 300 }}
                onSearch={(value) => {
                  setState(prev => ({ ...prev, searchKeyword: value }));
                  dispatch(fetchOrders({
                    page: 1,
                    limit: pagination.pageSize,
                    keyword: value,
                    status: state.filters.status,
                    paymentStatus: state.filters.paymentStatus,
                    paymentMethod: state.filters.paymentMethod,
                  }));
                }}
                enterButton={<SearchOutlined />}
              />
              <Select
                placeholder="订单状态"
                style={{ width: 120 }}
                allowClear
                onChange={(value) => {
                  setState(prev => ({
                    ...prev,
                    filters: { ...prev.filters, status: value || '' }
                  }));
                  dispatch(fetchOrders({
                    page: 1,
                    limit: pagination.pageSize,
                    keyword: state.searchKeyword,
                    status: value || '',
                    paymentStatus: state.filters.paymentStatus,
                    paymentMethod: state.filters.paymentMethod,
                  }));
                }}
              >
                <Option value="待付款">待付款</Option>
                <Option value="待发货">待发货</Option>
                <Option value="已发货">已发货</Option>
                <Option value="已完成">已完成</Option>
                <Option value="已取消">已取消</Option>
                <Option value="已退款">已退款</Option>
                <Option value="退款中">退款中</Option>
              </Select>
              <Select
                placeholder="支付状态"
                style={{ width: 120 }}
                allowClear
                onChange={(value) => {
                  setState(prev => ({
                    ...prev,
                    filters: { ...prev.filters, paymentStatus: value || '' }
                  }));
                  dispatch(fetchOrders({
                    page: 1,
                    limit: pagination.pageSize,
                    keyword: state.searchKeyword,
                    status: state.filters.status,
                    paymentStatus: value || '',
                    paymentMethod: state.filters.paymentMethod,
                  }));
                }}
              >
                <Option value="paid">已支付</Option>
                <Option value="unpaid">未支付</Option>
              </Select>
              <RangePicker
                placeholder={['开始日期', '结束日期']}
                onChange={(dates) => setState(prev => ({
                  ...prev,
                  filters: {
                    ...prev.filters,
                    dateRange: dates ? [dates[0]!.toISOString(), dates[1]!.toISOString()] : null
                  }
                }))}
              />
            </Space>
          </Col>
          <Col>
            <Space>
              <Button icon={<ReloadOutlined />} onClick={loadOrders}>
                刷新
              </Button>
              <Button icon={<ExportOutlined />}>
                导出
              </Button>
            </Space>
          </Col>
        </Row>
      </Card>

      {/* 订单表格 */}
      <Card>
        <Table
          columns={columns}
          dataSource={orders}
          rowKey="id"
          rowSelection={rowSelection}
          loading={loading}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) =>
              `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
            pageSizeOptions: ['10', '20', '50', '100'],
            onChange: (page, pageSize) => {
              // 更新分页并重新加载数据
              dispatch(fetchOrders({
                page,
                limit: pageSize,
                keyword: state.searchKeyword,
                status: state.filters.status,
                paymentStatus: state.filters.paymentStatus,
                paymentMethod: state.filters.paymentMethod,
              }));
            },
          }}
          scroll={{ x: 1200 }}
          size="middle"
        />
      </Card>
    </div>
  );
};

export default OrderList;
